//
//  DDTextViewEditViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/4/22.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDTextViewEditViewController.h"

#define MAX_TEXT_LENGTH   150

@interface DDTextViewEditViewController () <UITextViewDelegate>

@property (assign, nonatomic) NSInteger maxCharacterNumber;
@end

@implementation DDTextViewEditViewController

- (instancetype)initWithMaxCharacterNumber:(NSInteger)number
{
    if (self = [super init]) {
        
        _maxCharacterNumber = number;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = COLOR_BACKGROUND_GRAY;

    if (self.maxCharacterNumber == 0) {
        self.maxCharacterNumber = MAX_TEXT_LENGTH;
    }
    
    [self addLeftButtonItemWithImage:[UIImage imageNamed:@"back"] action:@selector(backButtonClick:)];
    [self addRightButtonItemWithImage:[UIImage imageNamed:@"common_save"] action:@selector(saveButtonClick:)];
    
    self.characterNumLabel.text = [NSString stringWithFormat:@"%d/%d",(int)[self.textView.text length],(int)self.maxCharacterNumber];
    [self setupSubviewLayout];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewEditChanged:)
                                                name:UITextViewTextDidChangeNotification object:self.textView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.textView becomeFirstResponder];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupSubviewLayout
{
    WEAKSELF
    
    UIView *textViewBgView = [[UIView alloc] init];
    textViewBgView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:textViewBgView];
    [textViewBgView addSubview:self.textView];
    [self.view addSubview:self.characterNumLabel];
    
    self.textView.delegate = self;
    
    [textViewBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view);
        make.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view).offset(15);
        make.height.mas_equalTo(200);
        
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textViewBgView.mas_left).offset(10);
        make.right.mas_equalTo(textViewBgView.mas_right).offset(-10);
        make.top.mas_equalTo(textViewBgView);
        make.bottom.mas_equalTo(textViewBgView);
        
    }];
    
    [self.characterNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view).offset(50);
        make.right.mas_equalTo(weakSelf.view).offset(-10);
        make.top.mas_equalTo(weakSelf.textView.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
        
    }];
}

- (void)setBlock:(TextBackBlock)block
{
    _block = [block copy];
}

#pragma mark
#pragma mark - Event Response

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    [self.view endEditing:YES];
}

- (void)backButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveButtonClick:(UIButton *)button
{
    if (_block) {
        _block(self.textView.text);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark  UITextViewDelegate

- (void)textViewEditChanged:(NSNotification *)obj
{
    UITextView *textView = (UITextView *)obj.object;
    
    NSString *toBeString = textView.text;
    
    NSString *lang = [textView.textInputMode primaryLanguage]; // 键盘输入模式
    
    NSUInteger maxLength = self.maxCharacterNumber; // 上限是10个汉字
    
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textView markedTextRange];
        
        //获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            if (toBeString.length > maxLength) {
                
                textView.text = [toBeString substringToIndex:maxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > maxLength) {
            
            textView.text = [toBeString substringToIndex:maxLength];
        }
    }
    
    if (!(toBeString.length > self.maxCharacterNumber)) {
        NSUInteger lenth = toBeString.length;
        if (lenth > self.maxCharacterNumber) {
            lenth = self.maxCharacterNumber;
        }
        self.characterNumLabel.text = [NSString stringWithFormat:@"%d/%d",(int)lenth,(int)self.maxCharacterNumber];
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    NSInteger number = [textView.text length];
    if (number > self.maxCharacterNumber) {

        textView.text = [textView.text substringToIndex:self.maxCharacterNumber];
        number = self.maxCharacterNumber;
    }
    
    self.characterNumLabel.text = [NSString stringWithFormat:@"%d/%d",(int)number,(int)self.maxCharacterNumber];
    
}


#pragma mark
#pragma mark - Getters and Setters

- (UITextView *)textView
{
    if (_textView == nil) {
        _textView = [[UITextView alloc] init];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.font = [UIFont systemFontOfSize:15.];
        if (self.value) {
            _textView.text = _value;
        }
    }
    
    return _textView;
}

- (UILabel *)characterNumLabel
{
    if (_characterNumLabel == nil) {
        _characterNumLabel = [[UILabel alloc] init];
        _characterNumLabel.textColor = COLOR_NAVIGATIONBAR;
        _characterNumLabel.font = [UIFont systemFontOfSize:13];
        _characterNumLabel.textAlignment = NSTextAlignmentRight;
    }
    
    return _characterNumLabel;
}

@end
